package com.aaa.doctor.service.impl;

import com.aaa.doctor.dto.RegPatDto;
import com.aaa.doctor.dto.RegistrationDto;
import com.aaa.doctor.feign.system.DeptFeign;
import com.aaa.doctor.feign.system.UserFeign;
import com.aaa.doctor.mapper.*;
import com.aaa.doctor.service.RegistrationServer;
import com.aaa.doctor.utils.IdWorker;
import com.aaa.doctor.vo.RegistrationVo;
import com.aaa.entity.*;
import com.aaa.utils.JwtUtil;
import com.aaa.utils.WebUtil;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author MuChengGuo
 * @date 2023/3/26 18:24
 * Description: TODO
 **/
@Service
public class RegistrationServerImpl implements RegistrationServer {
    @Autowired(required = false)
    private RegistrationMapper registrationMapper;
    @Autowired(required = false)
    private CareHistoryMapper careHistoryMapper;
    @Autowired(required = false)
    private PatientMapper patientMapper;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private DeptFeign deptFeign;

    /**
     * 条件查询挂号列表&分页
     *
     * @param registrationVo 条件
     * @return
     */
    @Override
    public Result<IPage<Registration>> getRegistrationList(Integer current, Integer size, RegistrationVo registrationVo) {
        QueryWrapper<Registration> wrapper = new QueryWrapper<>();
        if (Objects.nonNull(registrationVo.getDeptId())) {
            wrapper.eq("dept_id", registrationVo.getDeptId());
        }
        if (StringUtils.hasText(registrationVo.getPatientName())) {
            wrapper.eq("patient_name", registrationVo.getPatientName());
        }
        if (Objects.nonNull(registrationVo.getSchedulingType())) {
            wrapper.eq("scheduling_type", registrationVo.getSchedulingType());
        }
        if (Objects.nonNull(registrationVo.getSubsectionType())) {
            wrapper.eq("subsection_type", registrationVo.getSubsectionType());
        }
        if (Objects.nonNull(registrationVo.getRegStatus())) {
            wrapper.eq("registration_status", registrationVo.getRegStatus());
        }
        if (Objects.nonNull(registrationVo.getQueryData())) {
            wrapper.eq("registration_status", registrationVo.getQueryData());
        }
        IPage ipage = new Page(current, size);
        IPage<Registration> registrations = registrationMapper.selectPage(ipage, wrapper);
        return new Result<IPage<Registration>>(2000, "挂号列表查询成功", registrations);
    }

    @Override
    public Result<String> getCollect(String registrationId) {
        Registration registration = new Registration();
        registration.setRegistrationId(registrationId);
        registration.setRegistrationStatus("1");
        registrationMapper.updateById(registration);
        return new Result<String>(2000, "成功");
    }

    @Override
    public Result<String> getReturn(String registrationId) {
        Registration registration = new Registration();
        registration.setRegistrationId(registrationId);
        registration.setRegistrationStatus("4");
        registrationMapper.updateById(registration);
        return new Result<String>(2000, "成功");
    }

    @Override
    public Result<String> getInvalid(String registrationId) {
        Registration registration = new Registration();
        registration.setRegistrationId(registrationId);
        registration.setRegistrationStatus("5");
        registrationMapper.updateById(registration);
        return new Result<String>(2000, "成功");
    }

    @Override
    public Result<List<Registration>> queryToBeSeenRegistration(String schedulingType) {
        HttpServletRequest request = WebUtil.getRequest();
        String phone = (String) JwtUtil.getTokenChaim(request.getHeader("token")).get("username");
        Long userId = userFeign.getByUsername(phone).getUserId();

        QueryWrapper<Registration> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("scheduling_type", schedulingType);
        wrapper.eq("registration_status", '1');
        List<Registration> registrations = registrationMapper.selectList(wrapper);
        return new Result<>(2000, "成功", registrations);
    }

    @Override
    public Result<List<Registration>> queryVisitingRegistration(String schedulingType) {
        HttpServletRequest request = WebUtil.getRequest();
        String phone = (String) JwtUtil.getTokenChaim(request.getHeader("token")).get("username");
        Long userId = userFeign.getByUsername(phone).getUserId();

        QueryWrapper<Registration> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("scheduling_type", schedulingType);
        wrapper.eq("registration_status", "2");
        List<Registration> registrations = registrationMapper.selectList(wrapper);
        return new Result<>(2000, "成功", registrations);
    }

    @Override
    public Result<List<Registration>> handleVisit(String registrationId) {
        Registration registration = new Registration();
        registration.setRegistrationId(registrationId);
        registration.setRegistrationStatus("2");
        registrationMapper.updateById(registration);
        return new Result<>(2000, "成功");
    }

    @Override
    public Result<List<Registration>> queryVisitCompletedRegistration(String schedulingType) {
        HttpServletRequest request = WebUtil.getRequest();
        String phone = (String) JwtUtil.getTokenChaim(request.getHeader("token")).get("username");
        Long userId = userFeign.getByUsername(phone).getUserId();

        QueryWrapper<Registration> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("scheduling_type", schedulingType);
        wrapper.eq("registration_status", '3');
        List<Registration> registrations = registrationMapper.selectList(wrapper);
        return new Result<>(2000, "成功", registrations);
    }

    @Override
    public Result<String> addRegistration(RegPatDto regPatDto) {
        // 患者信息
        Patient patient = regPatDto.getPatientDto();

        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        wrapper.eq("id_card", patient.getIdCard());
        Patient patient1 = patientMapper.selectOne(wrapper);
        if (patient1 == null) {
            long l2 = new IdWorker().nextId();
            int i2 = new Random().nextInt(89) + 10;
            String pid = "HZ" + l2 + i2;
            patient.setPatientId(pid);
            patient.setIsFinal("0");
            patient.setCreateTime(new Date());
            patient.setUpdateTime(new Date());

            patientMapper.insert(patient);
        }

        // 挂号信息
        RegistrationDto registrationDto = regPatDto.getRegistrationDto();
        Registration registration = new Registration();

        //String id2 = "GH"+IdUtil.objectId();
        //String simpleUUID ="GH"+ IdUtil.simpleUUID();
        long l1 = new IdWorker().nextId();
        int i = new Random().nextInt(89) + 10;
        String iddd = "GH" + l1 + i;
        registration.setRegistrationId(iddd);

        registration.setPatientId(patient.getPatientId());
        registration.setPatientName(patient.getName());
        registration.setUserId(registrationDto.getUserId());

        List<User> allUser = userFeign.getListUser();
        for (User user : allUser) {
            if (user.getUserId().equals(registrationDto.getUserId())) {
                registration.setDoctorName(user.getUserName());
            }
        }
        deptFeign.getUpdNum(registrationDto.getDeptId(),registrationDto.getRegistrationNumber());

        registration.setDeptId(registrationDto.getDeptId());
        registration.setRegistrationItemId(registrationDto.getRegItemId());
        registration.setRegistrationAmount(registrationDto.getRegItemFee());
        registration.setRegistrationNumber(registrationDto.getRegistrationNumber());
        registration.setRegistrationStatus("0");
        registration.setVisitDate(registrationDto.getVisitDate());
        registration.setSchedulingType(registrationDto.getSchedulingType());
        registration.setSubsectionType(registrationDto.getSubsectionType());
        registration.setCreateTime(new Date());
        registration.setUpdateTime(new Date());

        HttpServletRequest request = WebUtil.getRequest();
        String phone = (String) JwtUtil.getTokenChaim(request.getHeader("token")).get("username");
        String userName = userFeign.getByUsername(phone).getUserName();

        registration.setCreateBy(userName);

        registrationMapper.insert(registration);

        return new Result<>(2000, "成功", registration.getRegistrationId());
    }

    /**
     * 挂号收费
     *
     * @param registrationId
     * @return
     */
    @Override
    public Result<String> collectFee(String registrationId) {
        Registration registration = new Registration();
        registration.setRegistrationId(registrationId);
        registration.setRegistrationStatus("1");
        registration.setUpdateTime(new Date());
        registrationMapper.updateById(registration);
        return new Result<>(2000, "成功");
    }

    @Override
    public Result<String> visitComplete(String registrationId) {
        Registration registration = new Registration();
        registration.setRegistrationId(registrationId);
        registration.setRegistrationStatus("3");
        registrationMapper.updateById(registration);
        return new Result<String>(2000, "成功");
    }

    @Override
    public Result<Integer> getRegistrationNumber(Long deptId) {

        Integer maxNum = registrationMapper.getMaxNum(deptId);
        if (maxNum == null) {
            return new Result<Integer>(2000, "成功", 0);
        }
        return new Result<>(2000, "成功", maxNum);
    }

    @Override
    public Result<CareHistory> getCareHistoryByRegId(String regId) {
        QueryWrapper<CareHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("reg_id", regId);
        CareHistory careHistory = careHistoryMapper.selectOne(wrapper);


        return new Result<>(2000, "成功", careHistory);
    }
}
